package com.fc.test.controller.gen;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import com.fc.test.common.base.BaseController;
import com.fc.test.common.domain.AjaxResult;
import com.fc.test.model.auto.HandleCase;
import com.fc.test.model.auto.HandleDatail;
import com.fc.test.model.custom.TableSplitResult;
import com.fc.test.model.custom.Tablepar;
import com.fc.test.model.custom.TitleVo;
import com.fc.test.service.HandleCaseService;
import com.fc.test.service.HandleDatailService;
import com.fc.test.util.SimpleEmailUtil;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.function.Function;
import java.util.stream.Collectors;

@Api(value = "服务事项")
@Controller
@RequestMapping("/HandleCaseController")
@ApiIgnore
public class HandleCaseController extends BaseController {

    private String prefix = "gen/handleCase";
    private static Logger logger = LoggerFactory.getLogger(SimpleEmailUtil.class);

    @Autowired
    private HandleCaseService handleCaseService;
    @Autowired
    private HandleDatailService handleDatailService;

    /**
     * 分页跳转
     */
    @ApiOperation(value = "分页跳转", notes = "分页跳转")
    @GetMapping("/view")
    @RequiresPermissions("gen:handleCase:view")
    public String view(ModelMap model) {
        String str = "服务事项";
        setTitle(model, new TitleVo("列表", str + "管理", true, "欢迎进入" + str + "页面", true, false));
        return prefix + "/list";
    }

    /**
     * 分页查询
     */
    //@Log(title = "服务事项集合查询", action = "111")
    @ApiOperation(value = "分页查询", notes = "分页查询")
    @PostMapping("/list")
    @RequiresPermissions("gen:handleCase:list")
    @ResponseBody
    public Object list(Tablepar tablepar, String searchText) {
        PageInfo<HandleCase> page = handleCaseService.list(tablepar, searchText);
        TableSplitResult<HandleCase> result = new TableSplitResult<HandleCase>(page.getPageNum(), page.getTotal(), page.getList());
        return result;
    }

    /**
     * 新增跳转
     */
    @ApiOperation(value = "新增跳转", notes = "新增跳转")
    @GetMapping("/add")
    public String add(ModelMap modelMap) {
        return prefix + "/add";
    }


    /**
     * 判断赋权要素 跳转 新增还是添加
     */
    @ApiOperation(value = "判断赋权要素跳转", notes = "判断赋权要素跳转")
    @GetMapping("/checkUrl/{id}")
    public String view2(@PathVariable("id") String id, ModelMap model) {
        HandleDatail handleDatail = handleDatailService.selectByPrimaryKey(id);

        if (Objects.isNull(handleDatail)) {
            handleDatail = new HandleDatail();
            handleDatail.setId(Integer.valueOf(id));
            return addDetail(handleDatail, model);
        } else {
            return editDetail(handleDatail, model);
        }

    }


    /**
     * 新增赋权要素跳转
     */
    @ApiOperation(value = "新增赋权要素跳转", notes = "新增赋权要素跳转")
    @GetMapping("/addDetail")
    public String addDetail(HandleDatail handleDatail, ModelMap modelMap) {
        modelMap.put("HandleDatail", handleDatail);
        return prefix + "/addDetail";
    }

    /**
     * 修改赋权要素跳转
     *
     * @param id
     * @param
     * @return ""
     */
    @ApiOperation(value = "修改赋权要素跳转", notes = "修改赋权要素跳转")
    @GetMapping("/editDetail")
    public String editDetail(HandleDatail handleDatail, ModelMap mmap) {
        mmap.put("HandleDatail", handleDatail);

        return prefix + "/editDetail";
    }


    /**
     * 新增
     */
    //@Log(title = "服务事项新增", action = "111")
    @ApiOperation(value = "新增", notes = "新增")
    @PostMapping("/add")
    @RequiresPermissions("gen:handleCase:add")
    @ResponseBody
    public AjaxResult add(HandleCase handleCase) {
        int b = handleCaseService.insertSelective(handleCase);
        if (b > 0) {
            return success();
        } else {
            return error();
        }
    }

    /**
     * 新增
     */
    //@Log(title = "赋权要素清单新增", action = "111")
    @ApiOperation(value = "新增", notes = "新增")
    @PostMapping("/addDetail")
    @RequiresPermissions("gen:handleCase:addDetail")
    @ResponseBody
    public AjaxResult add(HandleDatail handleDatail) {
        int b = handleDatailService.insert(handleDatail);
        if (b > 0) {
            return success();
        } else {
            return error();
        }
    }


    /**
     * 删除
     *
     * @param ids
     * @return
     */
    //@Log(title = "服务事项删除", action = "111")
    @ApiOperation(value = "删除", notes = "删除")
    @PostMapping("/remove")
    @RequiresPermissions("gen:handleCase:remove")
    @ResponseBody
    public AjaxResult remove(String ids) {
        int b = handleCaseService.deleteByPrimaryKey(ids);
        if (b > 0) {
            return success();
        } else {
            return error();
        }
    }

    /**
     * 检查Name
     *
     * @param
     * @return
     */
    @ApiOperation(value = "检查Name唯一", notes = "检查Name唯一")
    @PostMapping("/checkNameUnique")
    @ResponseBody
    public int checkNameUnique(HandleCase handleCase) {
        int b = handleCaseService.checkNameUnique(handleCase);
        if (b > 0) {
            return 1;
        } else {
            return 0;
        }
    }


    /**
     * 修改跳转
     *
     * @param id
     * @param mmap
     * @return
     */
    @ApiOperation(value = "修改跳转", notes = "修改跳转")
    @GetMapping("/edit/{id}")
    public String edit(@PathVariable("id") String id, ModelMap mmap) {
        mmap.put("HandleCase", handleCaseService.selectByPrimaryKey(id));

        return prefix + "/edit";
    }

    /**
     * 修改保存
     */
    //@Log(title = "服务事项修改", action = "111")
    @ApiOperation(value = "修改保存", notes = "修改保存")
    @RequiresPermissions("gen:handleCase:edit")
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(HandleCase record) {
        return toAjax(handleCaseService.updateByPrimaryKeySelective(record));
    }


    /**
     * 修改保存
     */
    //@Log(title = "赋权要素清单修改", action = "111")
    @ApiOperation(value = "修改保存", notes = "修改保存")
    @RequiresPermissions("gen:handleCase:editDetail")
    @PostMapping("/editDetail")
    @ResponseBody
    public AjaxResult editSave(HandleDatail record) {
        return toAjax(handleDatailService.updateByPrimaryKeySelective(record));
    }


    /**
     * 根据主键查询
     *
     * @param id
     * @param
     * @return
     */
    @ApiOperation(value = "根据id查询唯一", notes = "根据id查询唯一")
    @PostMapping("/get/{id}")
    public HandleCase edit(@PathVariable("id") String id) {
        return handleCaseService.selectByPrimaryKey(id);
    }


    /**
     * 导入文件跳转页面
     *
     * @return
     * @author fuce
     * @Date 2019年11月20日 下午10:19:03
     */
    @ApiOperation(value = "导入跳转", notes = "导入跳转")
    @GetMapping("/importExcel")
    public String importExcel(ModelMap modelMap) {
        return prefix + "/importExcel";
    }


    /**
     * 导入文件跳转页面
     *
     * @return
     * @author fuce
     * @Date 2019年11月20日 下午10:19:03
     */
    @ApiOperation(value = "导入详情页面跳转", notes = "导入详情页面跳转")
    @GetMapping("/importDetailExcel")
    public String importExcel2(ModelMap modelMap) {
        return prefix + "/importDetailExcel";
    }

    /**
     * 文件上传
     *
     * @param file
     * @return
     * @author fuce
     * @Date 2019年11月20日 下午10:18:49
     */
    //@Log(title = "文件上传", action = "1")
    @ApiOperation(value = "读取excel", notes = "读取excel")
    @PostMapping("/readExcel")
    @ResponseBody

    public AjaxResult updateAvatar(@RequestParam("file") MultipartFile file) {
        try {
            if (!file.isEmpty()) {

                System.out.println(file.getBytes().length);
                ImportParams params = new ImportParams();
                params.setTitleRows(1);
                params.setHeadRows(1);
                params.setNeedVerify(Boolean.TRUE);
                List<HandleCase> list = ExcelImportUtil.importExcel(file.getInputStream(), HandleCase.class, params);

                handleCaseService.batchInsert(list);

                return AjaxResult.successData(200, "添加数量：" + list.size());

            }
            return error();
        } catch (Exception e) {
            e.printStackTrace();
            return error(e.getMessage());
        }
    }

    /**
     * 要素清单文件上传
     *
     * @param file
     * @return
     * @author fuce
     * @Date 2019年11月20日 下午10:18:49
     */
    //@Log(title = "文件上传", action = "1")
    @ApiOperation(value = "读取要素清单excel", notes = "读取要素清单excel")
    @PostMapping("/readDetailExcel")
    @ResponseBody
    public AjaxResult updateAvatar2(@RequestParam("file") MultipartFile file) {
        try {
            if (!file.isEmpty()) {

                System.out.println(file.getBytes().length);
                ImportParams params = new ImportParams();
                params.setTitleRows(1);
                params.setHeadRows(1);
                params.setNeedVerify(Boolean.TRUE);
                List<HandleDatail> list = ExcelImportUtil.importExcel(file.getInputStream(), HandleDatail.class, params);

                if (list.size() == 0) {
                    return AjaxResult.error("表格内没有数据");
                }
                //根据excel 里的authname  查询四办列表
                List<HandleCase> handleCaseList = handleCaseService.queryByAuthNameList(list.stream().map(HandleDatail::getAuthName).collect(Collectors.toList()));


                //按照权限名称匹配   HandleCase-handleDatail   id是1对1  相等
                for (HandleDatail handleDatail : list) {
                    for (HandleCase handleCase : handleCaseList) {
                        if (handleDatail.getAuthName().trim().equals(handleCase.getAuthName().trim())) {
                            handleDatail.setId(handleCase.getId());
                            break;
                        }

                    }
                }
                //没有匹配上的 异常数据
                List<HandleDatail> exceptionData = new ArrayList<>();
                for(HandleDatail handleDatail : list){
                    if(handleDatail.getId() == null){
                        logger.info(handleDatail.toString());
                        exceptionData.add(handleDatail);
                    }
                }

                if(exceptionData.size()>0){
                    return AjaxResult.successData(201, exceptionData);
                }

                //能够匹配上的数据 （库里可能有的存在 有的不存在）
                list = list.stream().filter(HandleDatail -> (HandleDatail.getId() != null)).collect(Collectors.toList());


                //已经存在的HandleDatail 批量跟新
                List<HandleDatail> handleDatailList = handleDatailService.queryListByIds(handleCaseList.stream().map(HandleCase::getId).collect(Collectors.toList()));
                handleDatailService.updateBatch(handleDatailList);

                //剩下的插入
                Map<Integer, HandleDatail> map = handleDatailList.stream().collect(Collectors.toMap(HandleDatail::getId, Function.identity()));

                List<HandleDatail> insert = new ArrayList<>();
                for (HandleDatail a : list) {
                    HandleDatail handleDatail = map.get(a.getId());
                    if(Objects.isNull(handleDatail)){
                        insert.add(a);
                    }
                }


                if(insert.size()>0)
                handleDatailService.batchInsert(insert);



                return AjaxResult.successData(200, "添加数量：" + list.size());

            }
            return error();
        } catch (Exception e) {
            e.printStackTrace();
            return error(e.getMessage());
        }
    }

    /**
     * @param response
     * @throws Exception
     */
    @ApiOperation(value = "下载文件模版", notes = "下载文件模版")
    @GetMapping("/download")
    public void downloadLocal(HttpServletResponse response) throws Exception {
        // 下载本地文件
        ClassPathResource resource = new ClassPathResource("\\static\\download\\东亭街道马上办网上办就近办一次办不见面审批清单_模板.xlsx");
        // 读到流中
        InputStream inStream = resource.getInputStream();// 文件的存放路径
        // 设置输出的格式
        response.reset();
        response.setContentType("application/octet-stream");
        response.addHeader("Content-Disposition", "attachment; filename=\"" + URLEncoder.encode("东亭街道马上办网上办就近办一次办不见面审批清单_模板.xlsx", "utf-8") + "\"");
        // 循环取出流中的数据
        byte[] b = new byte[1000];
        int len;
        try {
            while ((len = inStream.read(b)) > 0)
                response.getOutputStream().write(b, 0, len);
            inStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
